<?php

class SJB_Admin_Miscellaneous_EmailLog extends SJB_Function
{
	public function isAccessible()
	{
		$this->setPermissionLabel('email_log');
		return parent::isAccessible();
	}
	
	public function execute()
	{
		$tp 		= SJB_System::getTemplateProcessor();
		$page 		= SJB_Request::getVar('page', 1);
		$restore 	= SJB_Request::getVar('restore', false);
		$action 	= SJB_Request::getVar('action', 'view_log');
		$action 	= $action == 'search' ? 'view_log' : $action;
		$sorting_field	= SJB_Request::getVar('sorting_field', 'date');
		$sorting_order 	= SJB_Request::getVar('sorting_order', 'DESC');
		$items_per_page = SJB_Request::getVar('items_per_page', 50);
		$display_error 	= SJB_Request::getVar('display_error', false);
		$errors = array();

		switch ($action) {
			case 'display_message':
				$sid = SJB_Request::getVar('sid', false);
				$email = SJB_EmailLogManager::getEmailInfoBySID($sid);
				$tp->assign('display_error', $display_error);
				$tp->assign('email', $email);
				$tp->display('display_log_message.tpl');
				break;

			case 'view_log':
				$userSID = SJB_Request::getVar('user_sid', false);
				if ($userSID) {
					$template = 'user_email_log.tpl';
					$_REQUEST['username']['equal'] = $userSID;
					$userInfo = SJB_UserManager::getUserInfoBySID($userSID);
					$userGroupInfo = SJB_UserGroupManager::getUserGroupInfoBySID($userInfo['user_group_sid']);
					$tp->assign('userGroupInfo', $userGroupInfo);
					$tp->assign('display_error', $display_error);
					$tp->assign('user_info', $userInfo);
					$tp->assign('user_sid', $userSID);
				}
				$email = new SJB_EmailLog($_REQUEST);
				$search_form_builder = new SJB_SearchFormBuilder($email);
				$criteria_saver = new SJB_EmailLogCriteriaSaver();
				if ($restore)
					$_REQUEST = array_merge($_REQUEST, $criteria_saver->getCriteria());

				$criteria = $search_form_builder->extractCriteriaFromRequestData($_REQUEST, $email);
				if (!$userSID) {
					$template = 'email_log.tpl';
					$search_form_builder->setCriteria($criteria);
					$search_form_builder->registerTags($tp);

					$tp->display("email_log_search_form.tpl");
				}
				$order_info = array('sorting_field' => $sorting_field,
					'sorting_order' => $sorting_order);
				$criteria_saver->setSessionForOrderInfo($order_info);
				$criteria_saver->setSessionForCurrentPage($page);
				$criteria_saver->setSessionForListingsPerPage($items_per_page);
				$searcher = new SJB_EmailLogSearcher(array('limit' => ($page - 1) * $items_per_page, 'num_rows' => $items_per_page), $sorting_field, $sorting_order);

				$found_emails = $searcher->getObjectsSIDsByCriteria($criteria);
				$criteria_saver->setSession($_REQUEST, $searcher->getFoundObjectSIDs());

				foreach ($found_emails as $id => $emailSID) {
					$emailInfo = SJB_EmailLogManager::getEmailInfoBySID($emailSID);
					$found_emails[$id] = $emailInfo;
					$found_emails[$id]['user'] = !empty($emailInfo['username']) ? SJB_UserManager::getUserInfoBySID($emailInfo['username']) : array();
					$found_emails[$id]['admin'] = array();
					if (!empty($emailInfo['admin'])) {
						if (is_numeric($emailInfo['admin']))
							$found_emails[$id]['admin'] = SJB_SubAdminManager::getSubAdminInfoBySID($emailInfo['admin']);
						else
							$found_emails[$id]['admin']['username'] = 'admin';
					}
				}

				$emailsCount = $searcher->getAffectedRows();
				$pages = array();
				for ($i = $page - 3; $i < $page + 3; $i++) {
					if ($i > 0)
						$pages[] = $i;
					if ($i * $items_per_page >= $emailsCount)
						break;
				}
				$totalPages = ceil($emailsCount / $items_per_page);
				if (empty($totalPages))
					$totalPages = 1;
				if (array_search(1, $pages) === false)
					array_unshift($pages, 1);
				if (array_search($totalPages, $pages) === false)
					array_push($pages, $totalPages);

				$searchFields = '';
				foreach ($_REQUEST as $key => $val) {
					if (is_array($val)) {
						foreach ($val as $fieldName => $fieldValue) {
							$searchFields .= "&{$key}[{$fieldName}]={$fieldValue}";
						}
					}
				}

				$tp->assign("searchFields", $searchFields);
				$tp->assign("currentPage", $page);
				$tp->assign("totalPages", $totalPages);
				$tp->assign("pages", $pages);
				$tp->assign("emailsCount", $emailsCount);
				$tp->assign("found_emails", $found_emails);
				$tp->assign("sorting_field", $sorting_field);
				$tp->assign("sorting_order", $sorting_order);
				$tp->assign("items_per_page", $items_per_page);
				$tp->display($template);
				break;
		}
	}
}